<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bootstrap - 增删改查</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="./js/bootstrap.min.js"></script>
</head>
<body>
    <!-- 表格 -->
    <div class="container" style="padding-top: 40px;">
        <div class="form-group">
            <div class="row">
                <div class="col-md-9">
                    <div class="col-sm-5">
                        <input type="text" class="form-control swich" id="bookNameSearch" placeholder="书籍名称"/>
                    </div>
                    <div class="col-sm-5">
                        <input type="text" class="form-control swich" id="authorSearch" placeholder="作者"/>
                    </div>
                        <button class="btn btn-danger sreach">搜索</button>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-default add" data-toggle="modal" data-target="#myModel">增加</button>
                    </div>
            </div>
        </div>
    </div>
        <table class="table table-bordered text-center">
            <tr>
                <td>书籍编号</td>
                <td>书籍名称</td>
                <td>作者</td>
                <td>出版日期</td>
                <td>书籍价格</td>
                <td>书籍类别</td>
                <td>操作</td>
            </tr>
            <tbody id="showMessage">

            </tbody>
        </table>
        <div class="row">
            <div id="show_page_info" class="col-md-4" style="line-height: 80px">
            </div>
            <div id="show_page_nav" class="col-md-8 text-right">
              <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                  <li class="disabled" jumpPageNum="1" id="pageone">
                    <a href="javascript:;">首页</a>
                  </li>
                  <li class="disabled" jumpPageNum="1">
                    <a href="javascript:;"><span>&laquo;</span></a>
                  </li>
                  <li jumpPageNum="${pageInfo.getPageNum()+1 }">
                    <a href="javascript:;"><span>&raquo;</span></a>
                  </li>
                  <li jumpPageNum="${pageInfo.getPages() }">
                    <a href="javascript:;">末页</a>
                  </li>
                </ul>
              </nav>
            </div>
          </div>
    </div>
    <!-- 修改的模态框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">修改信息</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <input type="text" placeholder="书籍编号" id="id" class="form-control" disabled/>
                        </div>
                        <div class="form-group">
                            <input type="text" placeholder="书籍名称" id="bookName" class="form-control" />
                        </div>
                        <div class="form-group">
                            <input type="text" placeholder="作者" class="author" id="author" />
                        </div>
                        <div class="form-group">
                            <input type="date" placeholder="出版日期" class="publicationDate" id="publicationDate" />
                        </div>
                        <div class="form-group">
                            <input type="text" placeholder="书籍价格" class="price" id="price" />
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary olk" data-dismiss="modal">提交更改</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal -->
    </div>
    <!-- 增加的模态框 -->
    <div class="modal fade" id="myModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">增加信息</h4>
                </div>
                <div class="modal-body">
                    <form  id="bookAddForm">
                        <div class="form-group">
                            <input type="text" placeholder="书籍名称" id="bookNameAdd" name="bookName" class="form-control" />
                        </div>
                        <div class="form-group">
                            <input type="text" placeholder="作者" id="authorAdd" name="author" class="form-control" />
                        </div>
                        <div class="form-group">
                            <input type="date" placeholder="出版日期" class="form-control" id="publicationDateAdd" name="publicationDate"/>
                        </div>
                        <div class="form-group">
                            <input type="text" placeholder="书籍价格" class="form-control" id="priceAdd" name="price"/>
                        </div>
                        <div class="form-group">
                            <input type="file" placeholder="书籍封面" class="form-control" id="bookImageFileAdd" name="bookImageFile"/>
                        </div>
                        <div class="form-group">
                            <img id="showPic" src="" class="img-thumbnail"/>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary aad" data-dismiss="modal">增加信息</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal -->
    </div>
    <script>
        //获取上传元素
        let bookFile = document.getElementById("bookImageFileAdd");
        bookFile.onchange = function (){
            //本地预览
            //获取用户选择的图片
            let file = this.files[0];
            console.log(file);
            //给选择图片创建一个url
            let url = URL.createObjectURL(file);
            console.log(file);
            //将地址交给img
            $('#showPic').attr('src',url);
        }

        
        $(function(){
            var bookName = "";
            var author = "";
            onleadOk(bookName,author,1);
        })
        //页面加载
        function onleadOk(bookName,author,pageNum){
            $.ajax({
                url:'http://localhost:8182/books/page',
                type:'get',
                data:{
                    bookName:bookName,
                    author:author,
                    pageNum:pageNum,
                },
                dataType:'json',
                success:function(data){
                    console.log(data)
                    if(!data.status){
                        alert(data.message);
                    }
                    var tbody = $('#showMessage');
                    tbody.empty(); // 清空现有的表格内容
                    //分页信息
                    let pageInfo =$("#show_page_info");
                    pageInfo.empty();
                    let span =`当前${data.data.pageNum}页,总${data.data.pages}页，总共${data.data.total}条记录`;
                    pageInfo.append(span);
                    var pageBox = $("#pageBox");
                    pageBox.empty();


                    //分页列
                    let pagination = $("#pagination");
                    pagination.empty();

                    //判断是否是首页
                    let firstdis = data.data.isFirstPage ? "disabled" : "";

                    //判断是否是末页
                    let enddis = data.data.isLastPage ? "disabled" : "";



                    //首页
                    let firstLi = `<li class="${firstdis}" jumpPageNum="1">
                                  <a href="javascript:;"><span>首页</span></a>
                                  </li>`;
                    pagination.append(firstLi);

                    let firstLiIcon = `<li class="${firstdis}" jumpPageNum="1">
                                  <a href="javascript:;"><span>&laquo;</span></a>
                                  </li>`;
                    pagination.append(firstLiIcon);


                    //循环页码
                    for (var i = 1; i <= data.data.pages; i++) {
                        let active = '';
                        if (data.pageNum == i) {
                            active = 'active';
                        }
                        let li = `<li class="${active}" jumpPageNum="${i}">
                                  <a href="javascript:;"><span>${i}</span></a>
                                  </li>`;
                        pagination.append(li);
                    }

                    //末页
                    let endLiIcon = `<li class="${enddis}" jumpPageNum="${data.pages}">
                                      <a href="javascript:;"><span>&raquo;</span></a>
                                      </li>`;
                    pagination.append(endLiIcon);

                    let endLi = `<li class="${enddis}" jumpPageNum="${data.pages}">
                                         <a href="javascript:;">末页</a>
                                  </li>`;
                    pagination.append(endLi);


                    
                    data.data.list.forEach(function(book) {
                        //展示图片
                        let bookPathUrl = book.pathUrl;
                        if(bookPathUrl == null){
                            bookPathUrl = "";
                        }else{
                            bookPathUrl = "http://localhost:8182/" + bookPathUrl;
                        }
                        var row = `<tr>
                                <td>${book.id}</td>
                                <td>${book.bookName}</td>
                                <td>
                                    <img style= "width:100px";height:100px; class="img-thumbnail" src='${bookPathUrl}'/>    
                                </td>
                                <td>${book.author}</td>
                                <td>${book.publicationDate}</td>
                                <td>${book.price}</td>
                                <td>${book.bookCategory.name}</td>
                        
                                <td>
                                    <button class="btn btn-primary rev" 
                                    data-toggle="modal" 
                                    data-target="#myModal"
                                    onclick="updateBook(${book.id})"
                                    >修改</button>
                                    <button class="btn btn-danger del" 
                                    onclick="deleteUser(${book.id})">删除</button>
                                </td>
                            </tr>
                        `;
                        tbody.append(row);
                    });
                }
            })
        }
        //删除的功能
        // $(document).on("click", ".del", function () {
        //     $(this).parents("tr").remove()
        // })
        function deleteUser(id){
            alert(id);
            $.ajax({
                url:'http://localhost:8182/books/'+ id,
                type:'Delete',
                success:function(data){
                    console.log(data);
                    alert(data);
                    onleadOk('','');
                    // if(data===1){
                    //     alert('删除成功')
                    // }  
                }
            })
        }
        //改的功能
        let book = {};

        function updateBook(id) {

            //获取后台数据

            $("#id").val(id);

            alert(id);

            $.ajax({

                url: "http://localhost:8182/books/" + id,

                type: "get",

                contentType: "application/json",

                success: function (data) {

                    console.log(data);

                    $("#id").val(data.id);

                    $("#bookName").val(data.bookName);

                    $("#author").val(data.author);

                    $("#publicationDate").val(data.publicationDate);

                    $("#price").val(data.price);

                    book = JSON.stringify(data);

                },

        });

    }

        //JSON.parse(string) ：接受一个 JSON 字符串并将其转换成一个 JavaScript 对象。

        //JSON.stringify(obj) ：接受一个 JavaScript 对象并将其转换为一个 JSON 字符串。

        $(document).on("click", ".olk", function () {

            

            book = JSON.parse(book);

            book.bookName = $("#bookName").val();

            book.author = $("#author").val();

            book.publicationDate = $("#publicationDate").val();

            book.price = $("#price").val();

            
            $.ajax({

            url: "http://localhost:8182/books",

            type: "put",

            contentType: "application/json", // 设置Content-Type

            data: JSON.stringify(book), // 发送JSON格式的数据

            success: function (data) {

                console.log(data);

                console.log(data);

                alert("修改成功！");

                var bookName = $("#bookNameSearch").val();

                var author = $("#authorSearch").val();

                onleadOk(bookName,author,1); // 刷新列表

            },
            });
        });
        //增加的功能
        // 在点击增加按钮时处理数据并发送
        $(document).on("click", ".aad", function () {
            // let bookName = $('#bookNameAdd').val();
            // let author = $('#authorAdd').val();
            // let publicationDate = $('#publicationDateAdd').val();
            // let price = $('#priceAdd').val();
            // let categoryId = 1;
            // let bookFile = $("#bookImageFileAdd").files[0];
            // const _arr = {bookName,author,publicationDate,price,categoryId,bookFile};
            // console.log(_arr); 
            //获取表单元素
            let form = document.querySelector('#bookAddForm');
            let formData = new FormData(form);
            // 使用JSON.stringify来确保发送的是一个JSON字符串
            $.ajax({
                url: 'http://localhost:8182/books',
                type: 'post',
                // contentType: 'application/json', // 设置Content-Type
                data: formData, //发送表单数据
                cache:false,    //设置为false 不需要从浏览器缓存，默认为true
                processData:false, //对数据的处理方式 默认为true，会将数据处理为对象格式
                contentType:false,  //需要设置为false，不然后台拿不到数据
                success: function (data) {
                    console.log(data);
                    alert("新增成功!")
                    onleadOk("","",1);//刷新列表
                }
            });
            //清除表单数据
            $('#myModal').find("input")
            .each(function(){
                $(this).val("");
            });
        });
        //查的功能
        $(".sreach").click(function () {
            var bookName = $("#bookNameSearch").val();
            var author =$("#authorSearch").val();
            onleadOk(bookName,author,1);

        });

    

        //点击页面 局部刷新
        $(document).on("click","#pagination li",function(){
                var bookName = $("#bookNameSearch").val();
                var author =$("#authorSearch").val();
                onleadOk(bookName,author,$(this).attr("jumpPageNum"));
        });
    </script>
</body>
</html>
